import { useStore } from '@/hooks';
import { Button, Dialog, Form, Input, Message, Switch } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { FieldsGrid, TitleGrid } from '../stores/definitions';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';
import TauTable from '@/components/TauTable';
import SubmitDialogComponent from './SubmitDialogComponent';

const FromItem = Form.Item;

const DataForm = ({ onCancel, modal, onSubmit, ...formProps }) => {
  const { companyStore: store } = useStore();
  const { show, record, toClose } = modal;
  const [member] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [isViewMode] = useState(show === 'view');
  const [state, setState] = useState([]);
  const [inputValue, setInputValue] = useState('');
  const [visible, setVisible] = useState(false);
  const [initMembers, setInitMembers] = useState([]);

  const [currentPage, setCurrentPage] = useState(0); // 默认页数
  const [pageSize, setPageSize] = useState(10); // 每页显示的数据数量

  useEffect(() => {
    if (toClose?.startsWith?.('toClose')) handleCancel();
  }, [modal]);

  useEffect(() => {
    (async () => {
      if (record?.id) {
        const res = await store.get(record?.id);
        const temp = store.assembleData(res?.memberPhones || [], res?.maintainVehiclePhones || []);
        setInitMembers(res?.memberPhones);
        setState(temp);
        editCtx.origin = _.cloneDeep(res);
        _.assign(member, res);
      }
      _.set(member, 'saveVehicle', true);
    })();
  }, [show]);

  const overrideModel = {
    companyName: {
      label: t`公司名称`,
      ui: {
        renderer: (v) => (
          <Input
            disabled={show === 'edit'}
            placeholder={t`请输入公司名称`}
            value={v}
          />),
        itemProps: { required: true },
      },
    },
  };

  const handleAddPhone = async () => {
    if (!inputValue) {
      Message.error(t`请输入手机号`);
      return;
    }
    const { companyName } = member;
    // 校验
    try {
      await store.validationPhone({ companyName, phone: inputValue, type: show === 'add' ? 'create' : 'update' });
    } catch (error) {
      Dialog.confirm({
        content: t`${error?.source?.message}, 无法加入！`,
      });
      return;
    }
    setState((pre) => {
      const arr = [...pre];
      arr.push({
        name: inputValue,
        saveVehicle: false,
      });
      return arr;
    });
    setInputValue(null);
  };

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(member, name, value);
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: ActivityForm.jsx:213 _ errors:', errors);
      return;
    }
    _.unset(member, 'phone_member');
    _.unset(member, 'phone_vehicle');
    // 数组去重
    const { members, vehicles } = store.separateData(state);
    _.set(member, 'memberPhones', toJS(members));
    _.set(member, 'maintainVehiclePhones', toJS(vehicles));
    if (initMembers?.length === state?.length) {
      onSubmit?.({ ...toJS(member), saveVehicle: false });
      return;
    }
    setVisible(true);
  };

  const handleDialogSubmit = (args) => {
    onSubmit?.(args);
    setVisible(false);
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleDeleteState = (i) => {
    setState((pre) => {
      const arr = [...pre];
      arr.splice(i + (currentPage * pageSize), 1);
      return arr;
    });
  };

  const handleOnSaveVehicle = (v, i) => {
    const cloneState = _.cloneDeep(state);
    cloneState[i].saveVehicle = v;
    setState(cloneState);
  };

  // 根据当前页码和每页数量获取当前页需要显示的数据
  const startIndex = currentPage * pageSize;
  const endIndex = startIndex + pageSize;
  const currentPageData = state.slice(startIndex, endIndex);

  return (
    <Form {...formProps} value={member} onChange={handleChange} inline useLabelForErrorMessage>
      <FieldsGrid formData={member} mode={show} overrideModel={overrideModel} fields={['companyName']} />
      <TitleGrid title={t`白名单设置`} />
      <>
        {show !== 'view' &&
          <Form.Item
            label={t`成员手机号`}
            labelAlign="left"
            name="phone_member"
            format="tel"
          >
            <Input
              value={inputValue}
              style={{ width: 300 }}
              placeholder="请输入手机号"
              onChange={(e) => setInputValue(e)}
              addonAfter={<Button type="primary" onClick={() => handleAddPhone()}>添加</Button>}
            />
          </Form.Item>
        }
        <Form.Item
          label={t`成员列表`}
          labelAlign="top"
          name="list"
          labelCol={
            { span: 8 }
          }
          wrapperCol={{
            span: 19,
          }}
        >
          <TauTable
            primaryKey="id"
            tableLayout="fixed"
            currentPage={currentPage}
            pageSize={pageSize}
            total={state.length}
            onFetch={({ page, size }) => {
              setCurrentPage(page);
              size && setPageSize(size);
            }}
            dataSource={currentPageData}
            columns={[
              { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.memberIdx(i, currentPage, pageSize) },
              {
                title: t`成员手机号`,
                dataIndex: 'name',
                width: 500,
                cell: (v) => v,
              },
              {
                title: t`是否可维护车辆`,
                dataIndex: 'saveVehicle',
                width: 500,
                cell: (v, i, r) => (
                  <Switch
                    checked={v}
                    autoWidth
                    unCheckedChildren={t`否`}
                    checkedChildren={t`是`}
                    onChange={(e) => handleOnSaveVehicle(e, i, r)}
                    size="small"
                  />
                ),
              },
              {
                title: t`操作`,
                dataIndex: '',
                width: 200,
                cell: (v, i) => <Button type="primary" text style={{ color: 'red' }} onClick={() => handleDeleteState(i)}>{t`移除`}</Button>,
              },
            ]}
          />
        </Form.Item>
      </>
      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
      <SubmitDialogComponent
        visible={visible}
        member={member}
        onSubmit={handleDialogSubmit}
        onClose={() => setVisible(false)}
      />
    </Form>
  );
};

export default observer(DataForm);
